<?php
class LRApi_history
{
	var $call = "";
	var $options = array();
	var $pagerOptions = array();

	function LRApiHistory ($lrAccount, $apiName, $secretWord, $options = null, $pagerOptions = null)
	{
		$this->call = new LRApi ($lrAccount, $apiName, $secretWord);
		if ($options != null) $this->options = $options;
		if ($pagerOptions != null) $this->pagerOptions = $pagerOptions;
	}

	function execute()
	{
		$authXml = $this->call->AuthXml();

		$options = $this->options;
		$pagerOptions = $this->pagerOptions;

		$xml = '<HistoryRequest id="' . $this->call->id . '">' . $authXml .
					'<History>' .
						'<AccountId>' . $this->call->lrAccount . '</AccountId>';

		if ($options != null)
		{
			foreach ($options as $key=>$value)
			{
				if ($value != "")
				$xml .= "<$key>$value</$key>";
			}
		}

		if ($pagerOptions != null)
		{
			$xml .= '<Pager>';
			foreach ($options as $key=>$value)
			{
				if ($value != "")
				$xml .= "<$key>$value</$key>";
			}
			$xml .= '</Pager>';
		}

		$xml .=	'</History></HistoryRequest>';

		$response = $this->call->getResponse("https://api.libertyreserve.com/xml/history.aspx?req=", $xml);

		if ($response != "")
		return $this->parseResponse ($response);
		else return "";
	}

	function parseResponse ($responseXml)
	{
		$response = array();

		$doc = new DOMDocument();
		if (!$doc->loadXML($responseXml))
		{
			$error = "Can't parse server's XML response.";
			return $response;
		}

		$rootElem = $doc->getElementsByTagName("HistoryResponse")->item(0);
		$responseId = $rootElem->getAttribute("id");

		if ($responseId != $this->call->id)
		{
			$error = "ResponseId does not match RequestId.";
			return $response;
		}

		// Get the Pager part
		$childElems = $rootElem->getElementsByTagName("Pager")->item(0);

		foreach ($childElems->getElementsByTagName("*") as $childNode)
		$response["Pager"][$childNode->nodeName] = $childNode->textContent;

		// Now get the Transaction(s)
		$counter = 0;

		$childElems = $rootElem->getElementsByTagName("Receipt");

		foreach ($childElems as $childNode)
		{
			$data = array();

			$children = $childNode->getElementsByTagName("*");
			foreach ($children as $child)
			{
				if ($child->nodeName != "Transfer")
				$data[$child->nodeName] = $child->textContent;
			};

			$response["Receipt"][$counter] = $data;
			$counter++;
		}

		return $response;
	}
}